//
//  CycleImageView.swift
//  EastNetWorkProject
//
//  Created by 伊伊 on 2023/12/22.
//

import UIKit
protocol CycleImageViewDelegate: NSObjectProtocol {
    func cycleImageviewWithImageView(_ imageView: UIImageView, indext: Int)
    func cycleImageview(_ imageView: UIImageView, didSelectItemAtIndexPath indext: Int)
}
class CycleImageView: UIView {
    
    weak var delegate: CycleImageViewDelegate?
    private var pagecontol: UIPageControl!{
        let pagecontol = UIPageControl()
        self.addSubview(pagecontol)
        pagecontol.translatesAutoresizingMaskIntoConstraints = false
        pagecontol.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -5).isActive = true
        pagecontol.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: 0).isActive = true
        pagecontol.widthAnchor.constraint(equalToConstant: 150).isActive = true
        pagecontol.heightAnchor.constraint(equalToConstant: 10).isActive = true

        pagecontol.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
     
        pagecontol.currentPageIndicatorTintColor = UIColor.red
        return pagecontol
        
    }
    
    var imagesArray: [String]!{
        didSet{
            self.pageCount = self.imagesArray.count
            self.pagecontol.numberOfPages = pageCount
            
            if imagesArray.isEmpty { return }
            self.collectionView.reloadData()
//            DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { [weak self] in
                self.addTimer()
           // }
        }
    }
    var completeBlock: ((UIImage) -> Void)?
    
    
   private var timer: Timer!
   private var  page = 0
   private var pageCount: NSInteger = 0
   private var collectionView: UICollectionView!
   
   private var flowout: UICollectionViewFlowLayout!
    override init(frame: CGRect) {
        super.init(frame: frame)
        let flowlayout = UICollectionViewFlowLayout()
        flowlayout.minimumLineSpacing = 0
        flowlayout.minimumInteritemSpacing = 0
        flowlayout.scrollDirection = .horizontal
        self.flowout = flowlayout
        
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowlayout)
        addSubview(collectionView)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.isPagingEnabled = true
        collectionView.isPrefetchingEnabled = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.backgroundColor = UIColor.white
        collectionView.register(CycleCollectionCell.self, forCellWithReuseIdentifier: "cell")
        collectionView.backgroundColor = UIColor.white
        self.collectionView = collectionView
        
       
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension CycleImageView{
    func startCycle() {
        addTimer()
    }
      
    func stopCycle() {
        removeTimer()
    }
      
    

   private func addTimer() {
        self.timer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(nextImage), userInfo: nil, repeats: true)
        RunLoop.current.add(timer, forMode: .common)
    }
      
    func removeTimer() {
        timer.invalidate()
        timer = nil
    }
      
    @objc func nextImage() {
        page += 1
        let section = page / pageCount
        let item = page % pageCount
        
        if section == 100 {
            let indexPath = IndexPath(item: 0, section: 0)
            collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
            page = 0
        } else {
            let indexPath = IndexPath(item: item, section: section)
            collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
        }
    }
    

    // MARK: - UIScrollViewDelegate
      
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let scrollW = scrollView.frame.size.width
        let page = Int((scrollView.contentOffset.x + scrollW * 0.5) / scrollW)
        if page > pageCount - 1 {
            self.page = page % pageCount
        }
        self.pagecontol.currentPage = page
    }
      
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        removeTimer()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        addTimer()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.collectionView.frame = self.bounds
    }

}



extension CycleImageView:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 100
    }
      
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return self.bounds.size
    }
      
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  
        return self.imagesArray.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CycleCollectionCell
        let urlString = self.imagesArray[indexPath.item]
        cell.imageView?.image = UIImage(named: urlString)
          
        return cell
    }
    
}
